import React, { useEffect, useState } from 'react'
import { Header, RouterView } from 'src/components'
import { deleteAddress } from 'src/api/getData'
import { Link } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { saveAddress } from 'src/redux/action'
import routerData from './routerData'
import './index.scss'

const Address = () => {

    const dispatch = useDispatch()
    const { userInfo, removeAddress } = useSelector(state => state)
    const [deletesite, setDeletesite] = useState(false) //是否编辑状态
    const [editText, setEditText] = useState('编辑')

    useEffect(() => {
        //初始化信息
        const initData = () => {
            if (userInfo && userInfo.user_id) {
                dispatch(saveAddress());
            }
        }
        initData()
    }, [userInfo, dispatch])


    //编辑
    const editThing = () => {
        if (editText === '编辑') {
            setEditText('完成');
            setDeletesite(true)
        } else {
            setEditText('编辑');
            setDeletesite(false)
        }
    }

    //删除地址
    const deleteSite = async (index, item) => {
        if (userInfo && userInfo.user_id) {
            await deleteAddress(userInfo.user_id, item.id);
            removeAddress.splice(index, 1);
        }
    }

    return <div className="page_profile_info_address">
        <Header title="编辑地址"
            goBack
            edit={<span className="edit" onClick={editThing}>{editText}</span>}
        > </Header>
        <section className="address">
            <ul className="addresslist">
                {
                    removeAddress.map((item, index) => {
                        return <li key={index}>
                            <div>
                                <p>{item.address}</p>
                                <p><span>{item.phone}</span>
                                    {item.phonepk && <span>、{item.phonepk}</span>}
                                </p>
                            </div>
                            {
                                deletesite && <div className="deletesite">
                                    <span onClick={() => deleteSite(index, item)}>x</span>
                                </div>
                            }
                        </li>
                    })
                }
            </ul>
            <Link to='/profile/info/address/addAddress'>
                <div className="addsite">
                    <span>新增地址</span>
                    <span className="addsvg">
                        <svg fill="#d8d8d8">
                            <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
                        </svg>
                    </span>
                </div>
            </Link>
        </section>
        <RouterView data={routerData} />
    </div>
}

export default Address